﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MuffinBreak.Bll
{
    partial class Vote
    {
        public DateTime Created
        {
            get
            {
                return CreatedUTC.ToLocalTime();
            }
        }

        public DateTime Updated
        {
            get
            {
                return UpdatedUTC.ToLocalTime();
            }
        }

        partial void OnValidate(System.Data.Linq.ChangeAction action)
        {
            if (action == System.Data.Linq.ChangeAction.Insert)
            {
                this.CreatedUTC = this.UpdatedUTC = DateTime.UtcNow;
            }
            else if (action == System.Data.Linq.ChangeAction.Update)
            {
                this.UpdatedUTC = DateTime.UtcNow;
            }
        }

        private static IQueryable<Vote> GetAllByEmailAddress(MuffinBreakDataContext context, string email)
        {
            return context.Votes.Where(x => x.EmailAddress == email);
        }

        public static bool HasVoted(MuffinBreakDataContext context, string email)
        {
            return GetAllByEmailAddress(context, email).Count() > 0;
        }

        public static Vote GetByEmailAddress(MuffinBreakDataContext context, string email)
        {
            return GetAllByEmailAddress(context, email).FirstOrDefault();
        }

        public static double GetPercentageByPostGuid(MuffinBreakDataContext context, Guid postGuid)
        {
            return context.Votes.Select(x => x.PostGuid == postGuid ? 1d : 0d).Average();
        }

        
    }
}
